from sys import flags
from flask import Blueprint,request
from flask.json import jsonify
from conf.comm import sqlalchemy_context
# 密码加密
from werkzeug.security import generate_password_hash
from database import *
import json
import re
import random
from views.redis import send_message
from utils.redisconn import r
#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()
def reg():
    data = request.data
    if not data:
        return jsonify({'code':10011})
    data = json.loads(data)

    # 正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not reg:
        return jsonify({'code':'10012','meg':'手机号不合法'})
 
    try:
        user = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code':200})
    except:
        return jsonify({'code':10010})



@bp_users.route('/sendsms',methods=['POST'])
def send():
    # 传递手机号
    data = json.loads(request.data)
    mobile = data['mobile']
    
    if not mobile:
        return jsonify({'code':20020,'meg':'请输入手机号'})
    else:
        pass
    # 用手机号去redis中去验证码，如果能取到返回，
    v = r.get_str(mobile)
    if v:
        return jsonify({'code':20021,'mes':'请30秒后发'})
        # 生成验证码
    code = str(random.randint(100000,999999))
    # 调用短信接口
    flag = send_message(mobile,code,1)
    if flag:
         # 发送成功，存入redis
        r.set_str(mobile,code,30)
        #  返回结果（验证码）
        return jsonify({'code':200,'smscode':code})
    else:
        return jsonify({'code':20011,'mes':'发送失败，请重试'}) 
